import xiors from 'xior'
import errorRetry from 'xior/plugins/error-retry'
import setupTokenRefresh from 'xior/plugins/token-refresh'
import { logger } from './logger'
import { Qs } from './querystring'

// 设置默认域名
const axios = xiors.create({
    baseURL: import.meta.env.WXT_API_URL,
    timeout: 10000
})

function getToken() {
    return localStorage.getItem('MZ_PLUGIN_TOKEN_KEY')
}

function deleteToken() {
    localStorage.removeItem('MZ_PLUGIN_TOKEN_KEY')
}

function shouldRefresh(response: any) {
    if (response?.status === 401) {
        // 401 表示需要重新登录
        deleteToken()
        setTimeout(() => {
            window.location.reload()
        }, 500)
        return false
    }
    return Boolean(response?.status && [403].includes(response.status))
}

setupTokenRefresh(axios, {
    shouldRefresh,
    async refreshToken(error) {
        try {
            const useInfoStr = localStorage.getItem('REVIEWER_ACCOUNT_SHOULD_RETRY_LOGIN')
            if (!useInfoStr) {
                setTimeout(() => {
                    window.location.reload()
                }, 500)
                logger.error('没有找到登录信息, 请重新登录')
                throw new Error('没有找到登录信息')
            }
            const userInfo = JSON.parse(useInfoStr)
            const tokenRefreshResponse = await axios.post(`${import.meta.env.WXT_API_URL}/api/login/doctorlogin`, Qs.stringify(userInfo))
            const token = tokenRefreshResponse.data?.token
            if (token) {
                localStorage.setItem('MZ_PLUGIN_TOKEN_KEY', token)
            } else {
                throw error
            }
        } catch (e) {
            // something wrong, delete old token
            deleteToken()
            logger.error('Token 刷新失败，可能是账号问题，需要重新登录！')
            setTimeout(() => {
                window.location.reload()
            }, 500)
            return Promise.reject(error)
        }
    }
})

axios.plugins.use(
    errorRetry({
        enableRetry: (config, error) => {
            if (error?.response && shouldRefresh(error.response)) {
                return true
            }
        }
    })
)

// 添加请求拦截器
axios.interceptors.request.use((config) => {
    config.headers['version'] = import.meta.env.WXT_VERSION

    const token = getToken()
    if (token) {
        config.headers['Authorization'] = token
    }

    config.headers['Persion_Id'] = localStorage.getItem('jhjk_login_id')
    // GET 请求避免缓存
    if (/get/i.test(config.method)) {
        config.params = config.params || {}
        // 添加时间戳
        config.params._ = new Date().getTime()
    }

    if (config.method == 'POST' && typeof config.data == 'string') {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }

    return config
})

// 添加响应拦截器
axios.interceptors.response.use(
    (response) => {
        return response.data
    },
    (error) => {
        return Promise.reject(error)
    }
)

export default axios
